package com.hugy.apollo.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
//特别注意这里的CSS_SERVICE_PLATFORM是apollo私有的命名空间，所谓私有的apollo私有命名空间创建在下面介绍
@EnableApolloConfig({"TEST1.hei.public"})
@Slf4j
public class ApolloPublicConfig implements ConfigChangeListener, InitializingBean {

    /**
     * 启用 apollo 配置中心②
     */
    @Bean
    public Config apolloConfig() {
        Config config = ConfigService.getConfig("TEST1.hei.public");
        config.addChangeListener(this);//设置监听
        return config;
    }

    /**
     * 监听配置变化
     */
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
        log.info("[changeHandler]Changes for namespace {}", changeEvent.getNamespace());
        for (String key : changeEvent.changedKeys()) {
            ConfigChange change = changeEvent.getChange(key);
            log.info("[changeHandler]Change - key: {}, oldValue: {}, newValue: {}, changeType: {}",
                    change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType());
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    }
}
